package iv1201project.model;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

/**
 * An interceptor that handles logging of a selected method.
 */
@Logthis
@Interceptor
public class LoggingInterceptor implements Serializable {
    
    /**
     * Write log about a method to a file.
     * 
     * @param ctx InvocationContext.
     * @return Object.
     * @throws Exception 
     */
    @AroundInvoke
    public Object logInvocation(InvocationContext ctx) throws Exception {
        // C:\Program\glassfish-3.1.1\glassfish\domains\domain1
        BufferedWriter out = new BufferedWriter(new PrintWriter(new FileWriter("log.txt", true)));
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        out.write("Time: " + dateFormat.format(date));
        out.newLine();
        out.write("Method: " + ctx.getMethod());
        out.newLine();
        out.write("Parameters: " + ctx.getParameters());
        out.newLine();
        out.newLine();
        out.flush();
        out.close();
        return ctx.proceed();
    }
}
